package fragments.shopactivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.travel.R;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import fragments.shopadapter.ShopSearchAdapter;
import fragments.shopadapter.TablayoutFragmentAdapter;
import fragments.shopfragment.GameFragment;
import fragments.shopfragment.GoodsFragment;
import fragments.shopfragment.ToFragment;
import fragments.shopfragment.TripFragment;
import fragments.shopfragment.ZhuantiFragment;
import shopbean.ShopSearchBean;
import tools.MyGridView;
import tools.MyListView;
import tools.Okhttputils;
import tools.RecordSQLiteOpenHelper;

/**
 * Created by Administrator on 2016/10/23.
 */
public class SearchActivity extends AppCompatActivity {
    @Bind(R.id.shop_search_gv)
    MyGridView shopSearchGv;
    @Bind(R.id.shop_search_ed)
    EditText shopSearchEd;
    @Bind(R.id.shop_tabLayout)
    TabLayout shopTabLayout;
    @Bind(R.id.shop_vp)
    ViewPager shopVp;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.tv2)
    TextView tv2;
    @Bind(R.id.listView)
    MyListView listView;
    private String searchcontent, serachContent;
    private List<ShopSearchBean.DataBean.HotPlacesBean> list;
    private BaseAdapter adapterQy;
    private ShopSearchAdapter adapter;
    private ToFragment toFragment = new ToFragment();
    private  TripFragment tripFragment=new TripFragment();
    private  ZhuantiFragment zhuantiFragment=new ZhuantiFragment();
    private  GameFragment gameFragment=new GameFragment();
    private  GoodsFragment goodsFragment=new GoodsFragment();
    private List<Fragment> listFragment = new ArrayList<>();
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    ;
    private SQLiteDatabase db;
    private TablayoutFragmentAdapter tablayoutFragmentAdapter;
    private String title[] = {"目的地", "行程", "专题", "轻游记", "商品",};
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            list = (List<ShopSearchBean.DataBean.HotPlacesBean>) msg.obj;
            adapter = new ShopSearchAdapter(list, SearchActivity.this);
            shopSearchGv.setAdapter(adapter);
        }
    };

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_search);
        ButterKnife.bind(this);
        initData();
        initLists();//添加Fragment
        for (int i = 0; i < title.length; i++) {
            shopTabLayout.addTab(shopTabLayout.newTab().setText(title[i]));
        }
        shopVp.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(shopTabLayout));
        shopTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                shopVp.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                queryData("");
            }
        });
        shopSearchEd.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = hasData(shopSearchEd.getText().toString().trim());
                    if (!hasData) {
                        insertData(shopSearchEd.getText().toString().trim());
                        queryData("");
                    }
                    shopSearchGv.setVisibility(View.GONE);
                    tv1.setVisibility(View.GONE);
                    tv2.setVisibility(View.GONE);
                    shopTabLayout.setVisibility(View.VISIBLE);
                    shopVp.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.GONE);
                    searchcontent = shopSearchEd.getText().toString();
                    try {
                        serachContent = URLEncoder.encode(searchcontent, "UTF-8");
                        Bundle bu = new Bundle();
                        bu.putString("bu", serachContent);
                        toFragment.setArguments(bu);
                        gameFragment.setArguments(bu);
                        goodsFragment.setArguments(bu);
                        tripFragment.setArguments(bu);
                        zhuantiFragment.setArguments(bu);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
        // 搜索框的文本变化实时监听
        shopSearchEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String tempName = shopSearchEd.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据
                // 根据tempName去模糊查询数据库中有没有数据
                queryData(tempName);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                shopSearchEd.setText(name);
            }
        });
        queryData("");
    }
    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }
    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象
        adapterQy = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"},
                new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        listView.setAdapter(adapterQy);
        adapterQy.notifyDataSetChanged();
    }
    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    private void initLists() {
        listFragment.add(toFragment);
        listFragment.add(tripFragment);
        listFragment.add(zhuantiFragment);
        listFragment.add(gameFragment);
        listFragment.add(goodsFragment);
        tablayoutFragmentAdapter = new TablayoutFragmentAdapter(getSupportFragmentManager(), listFragment);
        shopVp.setAdapter(tablayoutFragmentAdapter);
    }
    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run("http://m.api.youpu.cn/ypsearch/getHotPlace?paramType=get&sign=53a1b9bfe6719ae67716702f36dc93d2&package=a2&timestamp=1477229740");
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String hotPlaces = obj.getString("hotPlaces");
                    List<ShopSearchBean.DataBean.HotPlacesBean> listp = new ArrayList<ShopSearchBean.DataBean.HotPlacesBean>();
                    listp = JSONArray.parseArray(hotPlaces, ShopSearchBean.DataBean.HotPlacesBean.class);
                    Message message = new Message();
                    message.obj = listp;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
